package com.asset.inventory.network

import android.os.SystemClock
import com.asset.inventory.kt.logE
import com.asset.inventory.utils.SpHelper
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

/**
 *    @author : sibb
 *    date   : 21-4-7
 *    desc   : okhttp 配置项目
 */
object OkHttpConfig {

    // 连接时长
    private const val DEFAULT_CONNECT_TIMEOUT_MILLIS = 30 * 1000
    // 写入时长
    private const val DEFAULT_WIRTE_TIMEOUT_MILLS = 30 * 1000
    // 读取时长
    private const val DEFAULT_READ_TIMEOUOT_MILLS = 30 * 1000

    @Volatile
    private var mOkHttpClient: OkHttpClient

    init {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        mOkHttpClient = OkHttpClient.Builder()
            .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS.toLong(), TimeUnit.MILLISECONDS)
            .writeTimeout(DEFAULT_WIRTE_TIMEOUT_MILLS.toLong(), TimeUnit.MILLISECONDS)
            .readTimeout(DEFAULT_READ_TIMEOUOT_MILLS.toLong(), TimeUnit.MILLISECONDS)
            // 失败重连
            .retryOnConnectionFailure(false)
                // token持久化
             .addInterceptor(HeadInterceptor())
            // 打印网络信息
            .addInterceptor(httpLoggingInterceptor)

            .build()
    }

    fun getOkHttpClient(): OkHttpClient = mOkHttpClient

    class HeadInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {

            val request = chain.request()
            val builder = request.newBuilder()
            builder.addHeader("Authentication", SpHelper.getToken())
            return chain.proceed(builder.build())
        }
    }

//    class LoggerInterceptor(private val isDebug: Boolean = true): Interceptor{
//
//
//        override fun intercept(chain: Interceptor.Chain): Response {
//
//        }
//
//    }

}